package com.ruoyi.system.controller;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.Map;
import java.util.*;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.supplier.domain.TOrders;
import com.ruoyi.supplier.service.ITOrdersService;
import com.ruoyi.system.domain.TGoods;
import com.ruoyi.system.domain.TGoodsInorders;
import com.ruoyi.system.domain.TOrderDetail;
import com.ruoyi.system.domain.TSupplier;
import com.ruoyi.system.domain.chart.ChartInfo;
import com.ruoyi.system.mapper.TGoodsMapper;
import com.ruoyi.system.mapper.TOrderDetailMapper;
import com.ruoyi.system.service.ITGoodsInordersService;
import com.ruoyi.system.service.ITGoodsService;
import com.ruoyi.system.service.ITOrderDetailService;
import com.ruoyi.system.service.ITSupplierService;
import io.swagger.models.auth.In;
import org.apache.commons.math3.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/system/chart")
public class ChartController extends BaseController {

    @Autowired
    private ITGoodsService tGoodsService;

    @Autowired
    private ITGoodsInordersService tGoodsInordersService;

    @Autowired
    private ITSupplierService tSupplierService;

    @Autowired
    private ITOrdersService tOrdersService;

    /**
     * 商品销售量
     * @return
     */
    @GetMapping("/goodSalesVolume")
    public AjaxResult goodSalesVolume()
    {
        TGoods tGood = new TGoods();
        List<TGoods> tGoods = tGoodsService.selectTGoodsList(tGood);
        List<ChartInfo> chartInfos = new ArrayList<>();
        Map<String, Long> map = new HashMap<>();
        for (TGoods goods :tGoods) {
            String goodsId = goods.getGoodsId();
            TGoodsInorders sumAmountByGoodsId = tGoodsInordersService.getSumAmountByGoodsId(goodsId);
            map.put(goods.getGoodsName(),Long.parseLong("0"));
            if (sumAmountByGoodsId != null)
                map.put(goods.getGoodsName(),sumAmountByGoodsId.getAmount());
            else
                map.put(goods.getGoodsName(),Long.parseLong("0"));
        }
        List<Map.Entry<String, Long>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
            @Override
            public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
                if(o2.getValue()>o1.getValue())return 1;
                else if(o2.getValue()== o1.getValue()) return 0;
                return -1;
            }
        });
        int i=0;
        for (Map.Entry<String, Long> entry : list) {
            if(i>=10)break;
            ChartInfo chartInfo = new ChartInfo();
            chartInfo.setKey(entry.getKey());
            chartInfo.setValue(0L);
            if (entry.getValue() != null) chartInfo.setValue(entry.getValue());
            chartInfos.add(chartInfo);
            i++;
        }
        return success(chartInfos);
    }

    /**
     * 商品销售额
     * @return
     */
    @GetMapping("/goodSales")
    public AjaxResult goodSales()
    {
        TGoods tGood = new TGoods();
        List<TGoods> tGoods = tGoodsService.selectTGoodsList(tGood);
        List<ChartInfo> chartInfos = new ArrayList<>();
        for (TGoods goods :tGoods) {
            String goodsId = goods.getGoodsId();
            TGoodsInorders sumAmountByGoodsId = tGoodsInordersService.getSumAmountByGoodsId(goodsId);
            ChartInfo chartInfo = new ChartInfo();
            chartInfo.setKey(goods.getGoodsName());
            chartInfo.setValue(0L);
            if (sumAmountByGoodsId != null) chartInfo.setValue(sumAmountByGoodsId.getAmount() * goods.getPrice());
            chartInfos.add(chartInfo);
        }

        return success(chartInfos);
    }

    /**
     * 商人排行榜
     * @return
     */
    @Transactional
    @GetMapping("/bestBusinessman")
    public AjaxResult bestBusinessman()
    {
        List<ChartInfo> chartInfos = new ArrayList<>();
        List<TSupplier> tSuppliers = tSupplierService.selectTSupplierList(new TSupplier());
        HashMap<String, Long> map = new HashMap<>();
        for (TSupplier tSupplier : tSuppliers) {
            map.put(tSupplier.getSupplierName(), 0L);
        }

        TOrders tOrder = new TOrders();
        //拿到所有订单
        List<TOrders> tOrders = tOrdersService.selectTOrdersList(tOrder);
        for (TOrders orders : tOrders) {
            //拿到订单内所有的商品
            TGoodsInorders tGoodsInorder = new TGoodsInorders();
            tGoodsInorder.setOrderId(orders.getOrderId());
            List<TGoodsInorders> tGoodsInorders = tGoodsInordersService.selectTGoodsInordersList(tGoodsInorder);

            //统计商品与对应供应商的销售额
            for (TGoodsInorders goodsInorders : tGoodsInorders) {
                String goodsId = goodsInorders.getGoodsId();
                Long amount = goodsInorders.getAmount();
                TGoods tGoods = tGoodsService.selectTGoodsByGoodsId(goodsId);
                String supplierId = tGoods.getSupplierId();
                Long price = tGoods.getPrice();
                TSupplier tSupplier = tSupplierService.selectTSupplierBySupplierId(Long.parseLong(supplierId));
                String supplierName = tSupplier.getSupplierName();
                if ("供应商A".equals(supplierName)) {
                    System.out.println(tGoods.getGoodsName() + " : " + amount + " : " + price);
                }
                Long l = map.get(supplierName);
                if (amount != null) l += amount * price;
                map.put(supplierName, l);
            }
        }

        for (String s : map.keySet()) {
            Long val = map.get(s);
            ChartInfo chartInfo = new ChartInfo();
            chartInfo.setKey(s);
            chartInfo.setValue(val);
            chartInfos.add(chartInfo);
        }

        return success(chartInfos);
    }
    /**
     * 商人排行榜
     * @return
     */
    @Autowired
    ITOrderDetailService mapper;
    @Transactional
    @GetMapping("/theBusinessman")
    public AjaxResult theBusinessman()
    {

        List<ChartInfo> chartInfos = new ArrayList<>();
        List<TSupplier> tSuppliers = tSupplierService.selectTSupplierList(new TSupplier());
        List<Pair<String,Long>> map = new ArrayList<>();

        HashMap<Long, String> tmap = new HashMap<>();
        for (TSupplier tSupplier : tSuppliers) {
            tmap.put(tSupplier.getSupplierId(), tSupplier.getSupplierName());
        }
        HashMap<String,Long> tmap1=new HashMap<>();
        HashMap<String,Long> tmap2=new HashMap<>();
        List<TGoods> goods= tGoodsService.selectTGoodsList(new TGoods());

        for(TGoods tgood : goods) {
            tmap1.put(tgood.getGoodsId(),Long.parseLong(tgood.getSupplierId()));
            tmap2.put(tgood.getGoodsId(), tgood.getPrice());
        }
        TOrderDetail tOrder=new TOrderDetail();

        LocalDate firstDay = LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天

        Instant instant = firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant();

        Date date = Date.from(instant);
        tOrder.setCreateTime(date);
        //拿到所有订单
        List<TOrderDetail> tOrders = mapper.selectTOrderDetailList(tOrder);

        for(TOrderDetail tOrderDetail : tOrders) {
            TGoodsInorders tGoodsInorder = new TGoodsInorders();
            tGoodsInorder.setOrderId(tOrderDetail.getOrderId());
            List<TGoodsInorders> t = tGoodsInordersService.selectTGoodsInordersList(tGoodsInorder);
            if(t==null) {
                continue;
            }
            for(TGoodsInorders tGoodsInOrder : t){
                if(tmap1.get(tGoodsInOrder.getGoodsId())!=null&&tGoodsInOrder.getAmount()!=null&&tmap2.get(tGoodsInOrder.getGoodsId())!=null)
                map.add(new Pair<String,Long>(
                        tmap.get(tmap1.get(tGoodsInOrder.getGoodsId())),
                        tGoodsInOrder.getAmount()*tmap2.get(tGoodsInOrder.getGoodsId())));
            }
        }
        return success(map);
    }
}